/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include <stdlib.h>
#include <unconst.h>
#include <errno.h>

extern "C" double strtod(const char *s, char **sret) {
    long double r = 0.0;
    int e = 0;
    long double d;
    int sign = 1;
    int esign = 1;
    int i;
    int flags = 0;
    if(sret) {
        *sret = unconst(s, char *);
    }
    while((*s == ' ') || (*s == '\t')) {
        s++;
    }
    if(*s == '+') {
        s++;
    } else if(*s == '-') {
        sign = -1;
        s++;
    }
    while((*s >= '0') && (*s <= '9')) {
        flags |= 1;
        r *= 10.0;
        r += *s - '0';
        s++;
    }
    if(*s == '.') {
        d = 0.1L;
        s++;
        while((*s >= '0') && (*s <= '9')) {
            flags |= 2;
            r += d * (*s - '0');
            s++;
            d *= 0.1L;
        }
    }
    if(flags == 0) {
        return 0;
    }
    if(sret) {
        *sret = unconst(s, char *);
    }
    if((*s == 'e') || (*s == 'E')) {
        s++;
        if(*s == '+') {
            s++;
        } else if(*s == '-') {
            s++;
            esign = -1;
        }
        if((*s < '0') || (*s > '9')) {
            return r * sign;
        }
        while((*s >= '0') && (*s <= '9')) {
            e *= 10;
            e += *s - '0';
            s++;
        }
    }
    if(e < 0) {
        errno = ERANGE;
        r = HUGE_VAL;
    } else if(esign < 0) {
        for(i = 1; i <= e; i++) {
            r *= 0.1L;
            if(r < 2.47032822920623272088e-324L) {
                errno = ERANGE;
                r = 0.0;
                break;
            }
        }
    } else {
        for(i = 1; i <= e; i++) {
            r *= 10.0;
            if(r > DBL_MAX) {
                errno = ERANGE;
                r = HUGE_VAL;
                break;
            }
        }
    }
    if(sret) {
        *sret = unconst(s, char *);
    }
    return r * sign;
}
